#include "StdAfx.h"
#include "PeHelp.h"


bool CPeHelp::IsPe_practice(LPCSTR path)
{
	DWORD dwRead,dwMove;
	DWORD dwToNtHdr,dwNt;
	WORD wDos;
	HANDLE hFile;
	__try
	{
		hFile = CreateFile(path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
		if(hFile==INVALID_HANDLE_VALUE)
			return false;
		if(!ReadFile(hFile,&wDos,2,&dwRead,NULL) || dwRead!=2)
		{
			return false;
		}
		if(wDos!=0x5A4D)
		{
			return false;
		}
		dwMove = 0x3c;
		SetFilePointer(hFile,dwMove,NULL,FILE_BEGIN);
		if(!ReadFile(hFile,&dwToNtHdr,4,&dwRead,NULL) || dwRead!=4)
		{
			return false;
		}
		SetFilePointer(hFile,dwToNtHdr,NULL,FILE_BEGIN);
		if(!ReadFile(hFile,&dwNt,4,&dwRead,NULL) || dwRead!=4)
		{
			return false;
		}
		if(dwNt!=0x4550)
		{
			return false;
		}
		return true;
	}
	__finally
	{
		CloseHandle(hFile);
	}
}

bool CPeHelp::IsPe(LPCSTR path)
{
	HANDLE hFile=INVALID_HANDLE_VALUE,hMap=NULL;
	LPVOID pView = NULL;
	PIMAGE_DOS_HEADER pDos;
	PIMAGE_NT_HEADERS pNt;
	__try
	{
		hFile = CreateFile(path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
		if(hFile==INVALID_HANDLE_VALUE)
			return false;
		hMap = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL);
		if(hMap==NULL)
			return false;
		pView = MapViewOfFile(hMap,FILE_MAP_READ,0,0,0);
		if(pView==NULL)
			return false;
		pDos = (PIMAGE_DOS_HEADER)pView;
		if(pDos->e_magic!=0x5a4d)
		{
			return false;
		}
		pNt = (PIMAGE_NT_HEADERS)((PCHAR)pDos+pDos->e_lfanew);
		if(pNt->Signature!=(DWORD)0x4550)
			return false;
		
		return true;
	}
	__finally
	{
		if(pView)
			UnmapViewOfFile(pView);
		if(hMap)
			CloseHandle(hMap);
		if(hFile!=INVALID_HANDLE_VALUE)
			CloseHandle(hFile);
	}
}